import React, { useEffect, useState, memo } from 'react';
import { View, SafeAreaView, PermissionsAndroid, Platform, StyleSheet, Alert, ActivityIndicator, TouchableOpacity } from 'react-native';
import { Icon, Text, TopNavigation, Divider } from '@ui-kitten/components';
import { BleManager } from 'react-native-ble-plx';
import DeviceRender from '../components/DeviceList'
import Button from '../components/button'

import { useSelector, useDispatch } from 'react-redux';
import { addConnectedDevice, setCurrentConnectedDevice } from '../store'

async function requestBluetoothPermission() {
  if (Platform.OS === 'ios') {
    return true
  }
  if (Platform.OS === 'android' && PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION) {
    const apiLevel = parseInt(Platform.Version.toString(), 10)
    console.log(`api level ${apiLevel}`)
    if (apiLevel < 31) {
      const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
      return granted === PermissionsAndroid.RESULTS.GRANTED
    }
    if (PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN && PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT) {
      console.log('申请蓝牙权限')
      const result = await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
        PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
      ])
      console.log(`scan返回的${result['android.permission.BLUETOOTH_SCAN']}`)
      return (
        result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED &&
        result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED &&
        result['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED
      )
    }
  }

  return false
}

_showAlert = (title, message, callback) => {
  Alert.alert(
    title,
    message,
    [
      { text: '取消' },
      {
        text: '确定', onPress: () => { if (null != callback) { callback() } }
      }
    ]
  )
}

export default memo((props) => {
  const { navigation } = props

  const [deviceList, setDeviceList] = useState([])
  const [bleManager, setBleManager] = useState(null)
  const [bleState, setBleState] = useState(null)
  const [scanning, setCanning] = useState(false)
  const connectedDevices = useSelector((state) => {
    return state.devices.connectedDevices
  })

  const dispatch = useDispatch()

  _onOpenBluetooth = () => {
    if (Platform.OS === 'ios') {
      Linking.openURL('App-Prefs:root=Bluetooth')
    } else {
      bleManager.enable()
    }
  }

  // 蓝牙状态发生变化
  onBleStateChange = (state) => {
    console.log('蓝牙状态发生变化，新的状态为：', state)
    setBleState(state)
    if (state === 'PoweredOff') {
      _showAlert('未开启蓝牙', '请先开启蓝牙', _onOpenBluetooth)
    }
  }

  // 搜索设备
  scanDevices = () => {
    if (bleState === 'PoweredOn') {
      setDeviceList([])
      setCanning(true)
      bleManager.startDeviceScan(null, null, onScannedDevice)
      // bleManager.startDeviceScan(null, { allowDuplicates: false }, onScannedDevice)
    } else {
      _showAlert('未开启蓝牙', '请先开启蓝牙', _onOpenBluetooth)
    }
  }

  // 停止搜索设备
  stopScan = () => {
    if (scanning) {
      console.log('停止搜索设备')
      setCanning(false)
      bleManager.stopDeviceScan()
    }
  }

  clearDevices = () => {
    setDeviceList([])
  }

  // 搜索到设备
  onScannedDevice = (err, device) => {
    deviceName = device.localName || device.name
    if (!deviceName || deviceName.length < 1) {
      return
    }
    // if (deviceName.indexOf('HC') < 0) {
    //   return
    // }

    setDeviceList(prev => {
      if (prev.findIndex(item => item.id === device.id) < 0) {
        device.connecting = false
        return [...prev, device]
      }
      return prev
    })
  }

  _checkState = () => {
    bleManager.state()
      .then(state => {
        console.log('检查蓝牙状态：', state)
        setBleState(state)
        if (state === 'PoweredOff') {
          _showAlert('未开启蓝牙', '请先开启蓝牙', _onOpenBluetooth)
        }
      })
  }


  connectDevice = async (device) => {
    device.connecting = true
    const index = connectedDevices.findIndex(item => item.id === device.id)
    if (index >= 0) {
      dispatch(setCurrentConnectedDevice(connectedDevices[index]))
      Alert.alert('已经连接该设备了', null, [
        { text: '知道了' },
        { text: '去看看', onPress: () => navigation.push('Action') }
      ])
      return
    }
    if (scanning) {
      stopScan() // 连接时停止扫描
    }
    await device.connect()
    const serviceDevice = await device.discoverAllServicesAndCharacteristics();
    const services = await serviceDevice.services();
    for (const service of services) {
      const serviceUUID = service.uuid;
      const characteristics = await service.characteristics();
      for (const characteristic of characteristics) {
        const characteristicUUID = characteristic.uuid;
        //isReadable          
        if (characteristic.isWritableWithResponse || characteristic.isWritableWithoutResponse) {
          device.serviceUUID = serviceUUID
          device.characteristicUUID = characteristicUUID
          break
        }
      }
      if (device.serviceUUID) {
        break
      }
    }

    dispatch(addConnectedDevice(device))
    dispatch(setCurrentConnectedDevice(device))
    // dispatch(setCurrentConnectedDevice(device))

    Alert.alert('成功连接设备', null, [
      { text: '知道了' },
      { text: '去看看', onPress: () => navigation.push('Action') }
    ])
  }

  useEffect(() => {
    async function checkPer() {
      if (Platform.OS === "android" && !(await requestBluetoothPermission())) {
        _showAlert('提示', '没有获取到蓝牙权限')
      } else {
        _manager = new BleManager()
        _manager.onStateChange(onBleStateChange)
        setBleManager(_manager)
        _checkState()
      }
    }
    checkPer()

    return () => {
      //销毁时执行
      if (null != bleManager) {
        bleManager.destroy()
      }
    }
  }, [])

  const gotoConnected = () => {
    navigation.push('Connected')
  };


  const BackIcon = (props) => (
    <Icon {...props} name='arrow-right' />
  );

  const connectedAction = () => (
    <TouchableOpacity onPress={gotoConnected}>
      <Text style={{ color: "blue" }}>已连接设备</Text>
    </TouchableOpacity>
  );


  return (
    <SafeAreaView style={styles.container}>
      <TopNavigation title='搜索设备' alignment='center' accessoryRight={connectedAction} />
      <Divider />
      <View style={styles.header}>
        <Button
          style={{ marginRight: 16 }}
          onPress={scanDevices}
          disabled={scanning}
        >{scanning ? '正在搜索' : '开始搜索'}</Button>
        <Button
          onPress={stopScan}
          disabled={!scanning}
        >停止搜索</Button>
      </View>
      <View style={styles.listHeader}>
        <View style={styles.row}>
          <Text style={styles.headerTitle}>可用设备</Text>
          {scanning && <ActivityIndicator />}
        </View>
        <TouchableOpacity onPress={clearDevices}>
          <Text>清空</Text>
        </TouchableOpacity>
      </View>
      <DeviceRender
        onPress={connectDevice}
        data={deviceList}
        txtRight="连接"
      />
    </SafeAreaView>
  );
}, (prevProps, nextProps) => {
  return false
});

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  header: {
    flexDirection: 'row',
    padding: 15
  },
  listHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#f5f5f9',
    padding: 15
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerTitle: {
    fontSize: 15,
    marginRight: 6,
    fontWeight: '500',
  }
})